# set groupings of colors as palettes
dt_palettes <- list(
  `main`  = get_dt_cols("teal", "darkteal", "honeymustard"),
  `diverging` = get_dt_cols("darkteal", "lavender", "sand", "honeymustard"),
  `cool`  = get_dt_cols("darkteal", "teal", "seafoam", "lavender"),
  `desert`   = get_dt_cols("sand", "honeymustard", "rust", "cocoa"),
  `mixed` = get_dt_cols("cocoa", "rust","honeymustard", "sand", "lavender", "seafoam", "teal", "darkteal"),
  `grey`  = get_dt_cols("palegray", "darkgray")
)
theme_modest <- function(base_size = 12,
                                  base_family = "Roboto",
                                  base_line_size = base_size / 25,
                                  base_rect_size = base_size / 25) {
  require(grid)
  theme_minimal(base_size = base_size, 
                base_family = base_family,
                base_line_size = base_line_size)  %+replace%
    theme(
        axis.title = element_text(size = rel(0.85)),
        axis.text = element_text(size = rel(0.6)),
        axis.ticks=element_line(colour="grey", size=0.5),
        panel.grid.major = element_line(colour="grey", size=0.4),
        panel.grid.minor = element_line(colour="lightgrey", size=0.25),
        legend.box = NULL, 
        legend.text = element_text(size = rel(0.75)),
        legend.key.height = NULL,
        legend.key.width = NULL,
        legend.key = element_rect(fill = NA, colour = NA),
        legend.background = element_rect(colour = NA, fill=NA), 
        legend.position = "right",
        legend.justification = "center", 
        plot.background = element_rect(colour = NA, fill=NA),
        plot.margin = unit(c(0,0,0,0),"lines"),
        plot.title = element_text(size = rel(1.5), face = "bold", hjust="0.5",  margin = margin(t = 15)),
        plot.subtitle = element_text(size = rel(1.25), face = "bold", hjust="0.5",  margin = margin(t = 15)),
        plot.caption = element_text(size = rel(0.75), hjust = 1),
        strip.background = element_rect(colour = NA, fill=NA),
        strip.text = element_text(face = "bold", size = rel(1.25)),
        panel.spacing = unit(0,"lines"),
        panel.border=element_blank(),
        complete = TRUE
    )
}
  
  

theme_map_modest <- function(base_size = 12) {
  require(grid)
  theme_modest(base_size) %+replace%
    theme(
        axis.title.y = element_blank(),
        axis.title.x = element_blank(),
        axis.text = element_blank(),
        axis.ticks=element_blank(),
        panel.grid.minor.y=element_blank(),
        panel.grid.minor.x=element_blank(),
        panel.grid.major.x=element_blank(),
        panel.border=element_blank(),
        panel.spacing = unit(0,"lines"),
        plot.margin  =  unit(c(2,2,2,2),"lines")
    )
}

theme_set(theme_modest(base_size = 12))
# bus_licenses <- read_csv(here::here("data", "Business_Licenses.csv"))
bus_licenses <-  readRDS(here::here("data", "bus_licenses.Rda"))

# all_demos <-  readRDS(here::here("data", "all_demos_chi.Rda"))
all_demos.Chi <- readRDS(here::here("data", "all_demos_chi_proj.Rda"))
wards.2015 <-  readRDS(here::here("data", "wards2015_sf.Rda"))
chiCentralLongitude <- median(wards.2015$long)

ggplot(st_intersection(all_demos.Chi, wards.2015) %>% filter(!is.na(predominant_race))) +
  geom_sf(aes(fill=predominant_race, alpha=max_pct), lwd = 0) +
  scale_fill_dt("diverging", reverse=TRUE) +
  scale_alpha(range = c(0.35, 0.9), guide="none") + 
  geom_sf(data = wards.2015, color="black", fill=NA) +
    geom_text_repel(data=wards.2015 %>% filter(ward %in% c(10, 18)), 
                  aes(x=long, y=lat, label=ward),
                  fontface="bold",
                  force = 5,
                  size = 6,
                  direction = "both",
                  hjust=0) +
  geom_text_repel(data=wards.2015 %>% filter(ward %in% c(9, 13, 14, 33, 34)), 
                  aes(x=long, y=lat, label=ward),
                  nudge_x = -.35,
                  segment.size = 0.5,
                  segment.color = get_dt_cols("cocoa"),
                  fontface="bold",
                  size = 6,
                  force = 5,
                  direction = "both",
                  hjust=0) +
  geom_text_repel(data = wards.2015 %>% filter(ward %in% c(11)), 
                  aes(x=long, y=lat, label=ward),
                  nudge_x = .15,
                  segment.size = 0.5,
                  segment.color = get_dt_cols("cocoa"),
                  fontface="bold",
                  size = 6,
                  force = 10,
                  direction = "both",
                  hjust = 1) +
  coord_sf(datum = NA) +
  theme_map_modest() + 
  theme(plot.margin = unit(c(20, 0, 0, 0), "pt"),
        legend.title = element_text(size=15),
        legend.text = element_text(size=12),
        plot.title = element_text(size = 20, face = "bold", hjust="0.5", margin = margin(t = 15)),
        plot.subtitle = element_text(size = 15, margin = margin(t = 15)),
        plot.caption = element_text(size = 15)) +
  facet_wrap( ~ id) + labs(
    title = "Latinx Populations in Chicago\nPushed to South, West Neighborhoods",
    subtitle = "Chicago Racial and Ethnic Group Movement\nby Census Tract Since 2012 (5 year averages)",
    caption = "Source: U.S. Census Bureau", fill = "Predominant Race in Tract")

  turnoutSides <-  readRDS(here::here("data", "sides_turnout.Rda"))
  turnoutDiff <-  readRDS(here::here("data", "wards_turnout.Rda"))

  ggplot(turnoutSides, aes(x=as.factor(YEAR), y=TURNOUT, group=as.factor(SIDE))) + 
  geom_line(size=1.5, alpha=0.75, color="grey", show.legend = FALSE) +
  geom_line(data = filter(turnoutSides, (DIFFERENCE > -0)||(is.na(DIFFERENCE))), aes(colour=SIDE), size=1.5, show.legend=FALSE) +
  scale_color_dt("mixed", reverse = TRUE) + 
  geom_line(data = turnoutDiff, aes(group=as.factor(WARD), color=SIDE), size=0.5, alpha=0.25, show.legend = FALSE) +
  geom_label(data = turnoutDiff %>% group_by(YEAR, SIDE) %>% summarise(MEAN_TURNOUT = round(mean(TURNOUT, na.rm=TRUE),1)),
            aes(x=as.factor(YEAR), y= MEAN_TURNOUT, label = paste0(MEAN_TURNOUT, "%"), group=as.factor(SIDE)),
            color = "darkgray",
            label.padding = unit(0.05, "lines"),
            label.size = 0.0,
            fontface = "bold",
            size = 4) +
  geom_label_repel(data = turnoutSides %>% filter(YEAR == 2011),
            aes(label = paste0(SIDE), color = SIDE),
            fill=NA,
            hjust = "left",
            nudge_x = -.25,
            force=5,
            direction = "both",
            fontface = "bold",
            point.padding   = 3,
            size = 5,
            show.legend = FALSE) +
  geom_label_repel(data = turnoutSides %>% filter(YEAR == 2015),
            aes(label = paste0(SIDE), color = SIDE),
            fill=NA,
            hjust = "right",
            nudge_x = .25,
            force = 7.5,
            direction = "both",
            fontface = "bold",
            point.padding   = 3,
            size = 5,
            show.legend = FALSE) +
  scale_x_discrete(position = "top") +
   # coord_cartesian(ylim=c(23.5, 60)) +
  theme_modest() + 
  theme(axis.text.x.top = element_text(size=15, vjust = -8, face="bold"),
          axis.title.y = element_blank(),
          axis.title.x = element_blank(),
          axis.text.y = element_blank(),
          plot.caption = element_text(size = 12),
          panel.grid.minor=element_blank(),
          panel.grid.major=element_blank()) +
  labs(title="Highest Voter Turnout In Wards Facing Deinvestment", 
         subtitle="Change in Voter Turnout Between 2011 and 2015 Chicago City Council Elections", 
         caption="Source: Chicago Board of Election Commissioners", color="Chicago Area")

bus_licenses %>% filter(!is.na(WARD), active==1) %>%
  group_by(activity_month, activity_yr, WARD, SIDE) %>% 
  summarise(business_count = n()) %>% group_by(WARD) %>% arrange(desc(business_count)) %>% 
  ggplot(aes(x=reorder(WARD, business_count, FUN = median), y=business_count)) + 
  geom_boxplot(aes(group=as.factor(WARD), fill=as.factor(SIDE)), alpha=0.5) + 
  scale_fill_dt("mixed") +
  geom_text(data = bus_licenses %>% filter(!is.na(WARD), active==1) %>%
                    group_by(activity_month, activity_yr, WARD, SIDE) %>% 
                    summarise(business_count = n()) %>% group_by(WARD) %>% arrange(desc(business_count)) %>% 
                     summarise(median_issuances = median(business_count)) %>% arrange(median_issuances),
                   aes(x=as.factor(WARD), y = median_issuances + 8, group=as.factor(WARD), label=as.factor(WARD)),
            color="#6E2C49", fontface="bold") + 
  scale_y_continuous(limits = c(0, 750)) +
  # scale_x_discrete(breaks=seq(0,50,5)) + 
  labs(x="Chicago Council Ward", y="Average Monthly Business Count", caption="Data Source: Chicago Open Data Portal", title="Least New & Surviving Businesses in South, West Wards for 15+ Years", subtitle="Calumet Heights, Westlawn Average less than 25 Business License Issuances per month ",fill="Chicago Area") + 
  theme_modest() +
  theme(
        plot.margin = unit(c(20, 0, 0, 0), "pt"),
        panel.grid.major.x = element_blank(),
        axis.ticks =  element_blank(),
        axis.title =  element_text(size=12),
        legend.title = element_text(size=15),
        legend.text = element_text(size=12),
        axis.text.x = element_blank(),
        plot.title = element_text(size = 20, face = "bold", hjust="0.5", margin = margin(t = 15)),
        plot.subtitle = element_text(size = 15, margin = margin(t = 15)),
        plot.caption = element_text(size = 15)
        )

wards.shp.2015 <- here::here("data","Geofiles - Chicago Zip Code and Neighborhood","Boundaries - Wards (2015-)","geo_export_0bb2e9fd-20ca-415b-a96a-7722d72c1b41.shp")
wards2015 <- shapefile(wards.shp.2015)
wards2015@data <- mutate(wards2015@data, id = rownames(wards2015@data))
wards2015.points <- fortify(wards2015, region="id")
wards2015.df <- merge(wards2015.points, wards2015@data, by="id")
license_types <- c("ISSUE" = "New Business Licenses", 
                   "RENEW" = "Business License Renewals")  

bl <- bus_licenses %>% filter(activity_yr >= 2009, active == 1, `APPLICATION TYPE`%in% c('ISSUE', 'RENEW')) %>% 
    distinct(`LICENSE ID`, activity_yr, `APPLICATION TYPE`, LONGITUDE, LATITUDE) 
  
  ggmap::ggmap(ggmap::get_googlemap(center = c(lon = -87.732125, lat = 41.83379),
                      zoom = 10, scale = 1,
                      maptype ='terrain',
                      color = 'color',
                      key = Sys.getenv("GOOGLEMAPS_KEY"))) + 
    geom_point(data=bl, aes(x=LONGITUDE, y=LATITUDE, color=as.factor(activity_yr)), alpha = 0.05, show.legend = FALSE, na.rm = TRUE) + 
    geom_path(data = wards2015.df, aes(long,lat,group=group), color="black") +
    geom_polygon(data = wards2015.df, aes(long,lat,group=group), fill=NA) + 
    scale_color_dt("desert") +
    labs(y="Latitude", x="Longitude", colour="Year", title="Money in the Middle", 
         subtitle="Virtually No New Business Entry, Renwal in Chicago Wards 9, 10, 18, or 41 since\n2009", 
         caption = "Data Source: City of Chicago Department of Business Affairs and Consumer Protection"
         ) +
    theme_modest() + 
    facet_grid(. ~ `APPLICATION TYPE`, labeller=as_labeller(license_types)) +
    theme(
      panel.border = element_blank(),
      axis.text.y = element_blank(),
      panel.grid.major.y = element_blank(),
      panel.grid.minor.y = element_blank(),
      axis.title = element_blank(),
      axis.text.x = element_blank(),
      panel.grid.major.x = element_blank(),
      panel.grid.minor.x = element_blank(),
      plot.title = element_text(size = 20, face = "bold", hjust="0.5", margin = margin(t = 15)),
      plot.subtitle = element_text(size = 15,  hjust="0.5", margin = margin(t = 20)),
      plot.caption = element_text(size = 15)
    ) +
    scale_x_continuous(limits = c(wards2015.df %>% dplyr::select(long) %>% min() - 0.1, wards2015.df %>% dplyr::select(long) %>% max() + 0.05), expand = c(0, 0)) +
    scale_y_continuous(limits = c(wards2015.df %>% dplyr::select(lat) %>% min() - 0.1, wards2015.df %>% dplyr::select(lat) %>% max()) + 0.05, expand = c(0, 0))